/* ====================================================
 *                  全局导航栏功能
 * ==================================================== */
$(document).ready(function() {
    // 监听滚动事件
    $(window).scroll(function() {
        // 获取滚动位置
        const scrollPosition = $(this).scrollTop();
        const triggerPoint = 25; // 触发点，当滚动到 25px 时添加类名

        // 检查是否滚动到触发点
        if (scrollPosition >= triggerPoint) {
            // 添加类名
            $('body').addClass('nav-fixed');
        } else {
            // 移除类名
            $('body').removeClass('nav-fixed');
        }
    });

    // 监听点击事件
    $(document).on('click', '.mobile-nav-toggle', function(event) {
        // 切换 .mobile-main 和 .mobile-overlay 的显示状态
        $('.mobile-main').toggleClass('open');
        $('.mobile-overlay').toggle();
        event.stopPropagation(); // 阻止事件冒泡
    });

    // 监听点击遮罩层关闭
    $(document).on('click', '.mobile-overlay', function(event) {
        // 隐藏 .mobile-main 和 .mobile-overlay
        $('.mobile-main').removeClass('open');
        $('.mobile-overlay').hide();
    });

    // 点击其他地方关闭
    $(document).on('click', function(event) {
        // 检查是否在移动端视口
        if ($(window).width() < 768) {
            // 如果点击的不是 .mobile-main 或 .mobile-nav-toggle 的子元素，关闭 .mobile-main 和 .mobile-overlay
            if (!$(event.target).closest('.mobile-main, .mobile-nav-toggle').length) {
                $('.mobile-main').removeClass('open');
                $('.mobile-overlay').hide();
            }
        }
    });
});
/* ====================================================
 *                  首页幻灯片功能
 * ==================================================== */
document.addEventListener("DOMContentLoaded", () => {
    // 销毁旧实例避免重复初始化
    if ($('.single-list').hasClass('slick-initialized')) {
        $('.single-list').slick('unslick');
    }
    
    // 初始化新轮播实例
    $('.single-list').slick({
        autoplay: true,          // 自动播放
        autoplaySpeed: 3000,     // 自动播放速度(ms)
        dots: true,              // 显示指示点
        arrows: false,           // 隐藏箭头
        infinite: true,          // 无限循环
        slidesToShow: 1,         // 每次显示1张
        slidesToScroll: 1,       // 每次滚动1张
        fade: true, // 淡入淡出效果
        speed: 800,              // 切换速度(ms)
        cssEase: 'cubic-bezier(0.645, 0.045, 0.355, 1)',
        adaptiveHeight: true,    // 自适应高度
        pauseOnHover: true,      // 悬停暂停
        pauseOnFocus: true,      // 获取焦点时暂停
        responsive: [            // 响应式配置
            {
                breakpoint: 768,  // 768px以下配置
                settings: {
                    arrows: false,
                    dots: true
                }
            },
            {
                breakpoint: 480,  // 480px以下配置
                settings: {
                    arrows: false,
                    dots: true,
                    adaptiveHeight: false
                }
            }
        ]
    });
});
/* ====================================================
 *                  全局懒加载功能
 * ==================================================== */
(function() {
    // 多功能懒加载库
    class UnifiedLazyLoad {
        constructor(options = {}) {
            // 默认配置
            this.config = {
                // 图片懒加载配置
                imgSelector: 'img[data-src]',
                bgSelector: '[data-bg-src]',
                imgRootMargin: '200px 0px',
                imgThreshold: 0.01,
                imgLoadingClass: 'lazy-loading',
                imgLoadedClass: 'lazy-loaded',
                imgErrorClass: 'lazy-error',
                imgDataAttr: 'src',
                bgDataAttr: 'bg-src',
                defaultImage: '',
                useNativeLazyLoad: false,
                
                // 多媒体嵌入配置
                mediaSelector: 'media-embed',
                mediaRootMargin: '300px 0px',
                mediaThreshold: 0.01,
                
                // 通用配置
                throttleTime: 200
            };
            
            // 合并用户配置
            Object.assign(this.config, options);
            
            // 存储观察器实例
            this.imgObserver = null;
            this.mediaObserver = null;
            
            // 初始化
            this.init();
        }
        
        // 初始化方法
        init() {
            // 初始化图片懒加载
            this.initImageLazyLoad();
            
            // 初始化多媒体懒加载
            this.initMediaLazyLoad();
        }
        
        // 图片懒加载初始化
        initImageLazyLoad() {
            // 检查是否支持原生懒加载
            if (this.config.useNativeLazyLoad && 'loading' in HTMLImageElement.prototype) {
                this.initNativeImageLazyLoad();
            } 
            // 检查是否支持 IntersectionObserver
            else if ('IntersectionObserver' in window) {
                this.initIntersectionImageObserver();
            } 
            // 回退到传统滚动事件监听
            else {
                this.initScrollImageListener();
            }
        }
        
        // 多媒体懒加载初始化
        initMediaLazyLoad() {
            if ('IntersectionObserver' in window) {
                this.initIntersectionMediaObserver();
            } else {
                this.initScrollMediaListener();
            }
        }
        
        /* 图片懒加载相关方法 */
        initNativeImageLazyLoad() {
            const images = document.querySelectorAll(this.config.imgSelector);
            images.forEach(img => {
                img.loading = 'lazy';
                this.loadImage(img);
            });
            
            const bgElements = document.querySelectorAll(this.config.bgSelector);
            bgElements.forEach(el => {
                this.loadBackgroundImage(el);
            });
        }
        
        initIntersectionImageObserver() {
            this.imgObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const target = entry.target;
                        
                        if (target.tagName.toLowerCase() === 'img') {
                            this.loadImage(target);
                        } else if (target.hasAttribute(`data-${this.config.bgDataAttr}`)) {
                            this.loadBackgroundImage(target);
                        }
                        
                        observer.unobserve(target);
                    }
                });
            }, {
                rootMargin: this.config.imgRootMargin,
                threshold: this.config.imgThreshold
            });
            
            this.observeImageElements();
        }
        
        initScrollImageListener() {
            this.checkImageVisibility();
            
            let timer = null;
            const handler = () => {
                if (timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    this.checkImageVisibility();
                    timer = null;
                }, this.config.throttleTime);
            };
            
            window.addEventListener('scroll', handler);
            window.addEventListener('resize', handler);
        }
        
        observeImageElements() {
            document.querySelectorAll(this.config.imgSelector).forEach(img => {
                this.imgObserver.observe(img);
            });
            
            document.querySelectorAll(this.config.bgSelector).forEach(el => {
                this.imgObserver.observe(el);
            });
        }
        
        checkImageVisibility() {
            const scrollY = window.scrollY;
            const windowHeight = window.innerHeight;
            
            document.querySelectorAll(this.config.imgSelector).forEach(img => {
                if (this.isElementInViewport(img, scrollY, windowHeight, this.config.imgRootMargin) && 
                    !img.classList.contains(this.config.imgLoadedClass)) {
                    this.loadImage(img);
                }
            });
            
            document.querySelectorAll(this.config.bgSelector).forEach(el => {
                if (this.isElementInViewport(el, scrollY, windowHeight, this.config.imgRootMargin) && 
                    !el.classList.contains(this.config.imgLoadedClass)) {
                    this.loadBackgroundImage(el);
                }
            });
        }
        
        /* 多媒体懒加载相关方法 */
        initIntersectionMediaObserver() {
            this.mediaObserver = new IntersectionObserver((entries, observer) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const target = entry.target;
                        this.loadMediaContent(target);
                        observer.unobserve(target);
                    }
                });
            }, {
                rootMargin: this.config.mediaRootMargin,
                threshold: this.config.mediaThreshold
            });
            
            this.observeMediaElements();
        }
        
        initScrollMediaListener() {
            this.checkMediaVisibility();
            
            let timer = null;
            const handler = () => {
                if (timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    this.checkMediaVisibility();
                    timer = null;
                }, this.config.throttleTime);
            };
            
            window.addEventListener('scroll', handler);
            window.addEventListener('resize', handler);
        }
        
        observeMediaElements() {
            document.querySelectorAll(this.config.mediaSelector).forEach(el => {
                this.mediaObserver.observe(el);
            });
        }
        
        checkMediaVisibility() {
            const scrollY = window.scrollY;
            const windowHeight = window.innerHeight;
            
            document.querySelectorAll(this.config.mediaSelector).forEach(el => {
                if (this.isElementInViewport(el, scrollY, windowHeight, this.config.mediaRootMargin) && 
                    !el.classList.contains('loaded')) {
                    this.loadMediaContent(el);
                }
            });
        }
        
        /* 通用方法 */
        isElementInViewport(el, scrollY, windowHeight, margin = '0px') {
            const rect = el.getBoundingClientRect();
            const marginValue = parseInt(margin, 10) || 0;
            
            return (
                rect.bottom >= -marginValue &&
                rect.top <= (windowHeight + marginValue)
            );
        }
        
        // 加载图片
        loadImage(img) {
            img.classList.add(this.config.imgLoadingClass);
            
            if (this.config.defaultImage && !img.src) {
                img.src = this.config.defaultImage;
            }
            
            const newImg = new Image();
            newImg.src = img.getAttribute(`data-${this.config.imgDataAttr}`);
            
            newImg.onload = () => {
                img.classList.remove(this.config.imgLoadingClass);
                img.classList.add(this.config.imgLoadedClass);
                img.src = newImg.src;
                this.triggerEvent(img, 'lazyloaded');
            };
            
            newImg.onerror = () => {
                img.classList.remove(this.config.imgLoadingClass);
                img.classList.add(this.config.imgErrorClass);
                this.triggerEvent(img, 'lazyerror');
            };
        }
        
        // 加载背景图
        loadBackgroundImage(el) {
            el.classList.add(this.config.imgLoadingClass);
            const bgUrl = el.getAttribute(`data-${this.config.bgDataAttr}`);
            
            const img = new Image();
            img.src = bgUrl;
            
            img.onload = () => {
                el.classList.remove(this.config.imgLoadingClass);
                el.classList.add(this.config.imgLoadedClass);
                el.style.backgroundImage = `url(${bgUrl})`;
                this.triggerEvent(el, 'lazyloaded');
            };
            
            img.onerror = () => {
                el.classList.remove(this.config.imgLoadingClass);
                el.classList.add(this.config.imgErrorClass);
                this.triggerEvent(el, 'lazyerror');
            };
        }
        
        // 加载多媒体内容
        loadMediaContent(el) {
            const iframe = el.querySelector('iframe');
            if (iframe && iframe.dataset.src) {
                iframe.src = iframe.dataset.src;
                el.classList.add('loaded');
                this.triggerEvent(el, 'medialoaded');
            }
        }
        
        // 触发自定义事件
        triggerEvent(element, eventName) {
            const event = new Event(eventName, { bubbles: true, cancelable: true });
            element.dispatchEvent(event);
        }
        
        // 销毁实例
        destroy() {
            if (this.imgObserver) {
                this.imgObserver.disconnect();
                this.imgObserver = null;
            }
            
            if (this.mediaObserver) {
                this.mediaObserver.disconnect();
                this.mediaObserver = null;
            }
            
            window.removeEventListener('scroll', this.checkImageVisibility);
            window.removeEventListener('resize', this.checkImageVisibility);
            window.removeEventListener('scroll', this.checkMediaVisibility);
            window.removeEventListener('resize', this.checkMediaVisibility);
        }
    }
    
    // 全局暴露 API
    window.UnifiedLazyLoad = UnifiedLazyLoad;
    
    // 自动初始化
    document.addEventListener('DOMContentLoaded', () => {
        new UnifiedLazyLoad();
    });
})();
/* ====================================================
 *                  评论加载功能
 * ==================================================== */
document.addEventListener("DOMContentLoaded", () => {
    function initCommentLoader() {
    var commentList = document.querySelector('.comment-list');
    if (!commentList) return;
    
    var isLoading = false;
    var noMoreComments = false;
    var loadingSpinner = document.getElementById('loading-spinner');
    var noMoreElement = document.getElementById('no-more');

    function loadMoreComments() {
        if (isLoading || noMoreComments) return;

        var nextPageUrl = document.querySelector('.page-navigator .next a')?.getAttribute('href');
        if (!nextPageUrl) {
            noMoreComments = true;
            if (noMoreElement) noMoreElement.style.display = 'block';
            if (loadingSpinner) loadingSpinner.style.display = 'none';
            return;
        }

        isLoading = true;
        if (loadingSpinner) loadingSpinner.style.display = 'flex';

        setTimeout(function () {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', nextPageUrl, true);
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var tempDiv = document.createElement('div');
                    tempDiv.innerHTML = xhr.responseText;

                    var newComments = tempDiv.querySelector('.comment-list')?.innerHTML;
                    if (newComments) {
                        commentList.insertAdjacentHTML('beforeend', newComments);
                        // Highlight new code blocks
                        document.querySelectorAll('pre code').forEach((block) => {
                            hljs.highlightElement(block);
                        });
                    }

                    var newNav = tempDiv.querySelector('.page-navigator')?.innerHTML;
                    if (newNav) {
                        document.querySelector('.page-navigator').innerHTML = newNav;
                    }

                    if (!tempDiv.querySelector('.page-navigator .next a')) {
                        noMoreComments = true;
                        if (noMoreElement) noMoreElement.style.display = 'block';
                    }
                } else {
                    console.error('Request failed: ' + xhr.statusText);
                }
                isLoading = false;
                if (loadingSpinner) loadingSpinner.style.display = 'none';
            };
            xhr.onerror = function () {
                console.error('Request failed');
                isLoading = false;
                if (loadingSpinner) loadingSpinner.style.display = 'none';
            };
            xhr.send();
        }, 500);
    }

    function handleScroll() {
        if (isLoading || noMoreComments) return;

        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;

        if (scrollTop + clientHeight >= scrollHeight - 200) {
            loadMoreComments();
        }
    }
    
    // Initialize scroll listener
    window.addEventListener('scroll', handleScroll);

    // Check initial state
    var initialNextPageUrl = document.querySelector('.page-navigator .next a')?.getAttribute('href');
    if (!initialNextPageUrl) {
        noMoreComments = true;
        if (noMoreElement) noMoreElement.style.display = 'block';
        if (loadingSpinner) loadingSpinner.style.display = 'none';
    }

    // Highlight any existing code blocks on page load
    document.querySelectorAll('pre code').forEach((block) => {
        hljs.highlightElement(block);
    });

    // Return cleanup function for PJAX
    return function() {
        window.removeEventListener('scroll', handleScroll);
    };
}

// Initial load 
var cleanupCommentLoader = initCommentLoader();

})
